package handler

import (
	"context"
	"errors"
	"four/sss/weeekrpc/weeekrpcclient"
	"io"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"

	"four/sss/weeekapi/internal/logic"
	"four/sss/weeekapi/internal/svc"
	"four/sss/weeekapi/internal/types"
	"github.com/zeromicro/go-zero/rest/httpx"
)

func UploadHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		//todo: 文件格式、大小处理
		file, h, err := r.FormFile("file")
		userid := r.Form.Get("userid")
		if err != nil {
			log.Println("文件接收失败")
			httpx.ErrorCtx(r.Context(), w, errors.New("文件接收失败"))
			return
		}
		if h.Size > 1024*1024*5 {
			log.Println("文件过大")
			httpx.ErrorCtx(r.Context(), w, errors.New("文件过大"))
			return
		}
		Filetype := []string{"png", "gif", "jpg", "jpeg", "GIF", "PNG", "JPG", "JPEG", "DOC", "doc", "mp4", "mp3", "MP3", "MP4"}
		sux := strings.Split(h.Filename, ".")
		suxName := sux[1]
		if !strings.Contains(strings.Join(Filetype, "."), suxName) {
			log.Println("文件格式有误")
			httpx.ErrorCtx(r.Context(), w, errors.New("文件格式有误"))
			return
		}
		//todo: 调用rpc查询容量
		id, _ := strconv.Atoi(userid)
		res, err := svcCtx.WeekRpc.Capacity(context.Background(), &weeekrpcclient.CapacityRequest{
			Userid: int64(id),
		})
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}
		//todo: 该用户可上传的文件总容量
		vip := (res.VipLv + 50) * 1024 * 1024
		//todo: 已上传容量+本次文件大小
		capacity := res.Capacity + h.Size
		if vip < capacity {
			httpx.ErrorCtx(r.Context(), w, errors.New("容量不足了哦"))
			return
		}
		//todo: 容量充足，文件上传
		//todo: 随机数重构文件名
		t := strconv.Itoa(int(time.Now().Unix()))
		fileName := t + "." + suxName
		newsrc := "./static/" + fileName
		//./static/: is a directory
		opens, err := os.OpenFile(newsrc, os.O_WRONLY|os.O_CREATE, 0777)
		log.Println(err, "/////////////////")
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, errors.New("文件路径有误"))
			return
		}
		_, err = io.Copy(opens, file)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, errors.New("文件上传失败"))
			return
		}
		r.Form.Set("userid", userid)
		r.Form.Set("file", fileName)                        //todo: 文件名
		r.Form.Set("fileName", suxName)                     //todo: 文件后缀
		r.Form.Set("capacity", strconv.Itoa(int(capacity))) //todo: 上传后用户容量
		r.Form.Set("size", strconv.Itoa(int(h.Size)))
		r.Form.Set("src", newsrc)

		var req types.UploadRequest
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := logic.NewUploadLogic(r.Context(), svcCtx)
		resp, err := l.Upload(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}
